const express = require("express");
const router = express.Router();
const path = require("path");
const ManagerService = require(path.join(
  process.cwd(),
  "/services/ManagerService"
));

//查询用户
router.get(
  "/",
  (req, res, next) => {
    if (!req.query.pagenum || req.query.pagenum <= 0)
      return res.sendResult(null, 400, "pagenum 参数错误");
    if (!req.query.pagesize || req.query.pagesize <= 0)
      return res.sendResult(null, 400, "pagesize 参数错误");
    next();
  },
  (req, res, next) => {
    const { query, pagenum, pagesize } = req.query;
    ManagerService.getManagers(
      {
        query,
        pagenum,
        pagesize,
      },
      function (err, result) {
        if (err) return res.sendResult(500, null, err);
        res.sendResult(200, result, "获取管理员列表成功");
      }
    );
  }
);

//创建用户
router.post(
  "/",
  (req, res, next) => {
    if (!req.body.username) {
      return res.sendResult(400, null, "用户名不能为空");
    }
    if (!req.body.password) {
      return res.sendResult(400, null, "密码不能为空");
    }
    if (!req.body.rid || isNaN(parseInt(req.body.rid))) {
      req.body.rid = -1;
    }
    next();
  },
  (req, res, next) => {
    const { username, password, mobile, email, rid } = req.body;
    const params = { username, password, mobile, email, rid };
    ManagerService.createManagers(params, function (err, result) {
      if (err) return res.sendResult(500, null, err);
      res.sendResult(200, result, "创建成功");
    });
  }
);

//修改
router.put(
  "/:id",
  (req, res, next) => {
    //   /1?roleId=1 req.params req.query  { id: '1' } { roleId: '1' }
    if (!req.params.id) {
      return res.sendResult(400, null, "用户ID不能为空");
    }
    if (isNaN(parseInt(req.params.id)))
      return res.sendResult(400, null, "用户ID必须是数字");
    next();
  },
  (req, res, next) => {
    ManagerService.modifyManagers(
      {
        id: req.params.id,
        mobile: req.body.mobile,
        email: req.body.email,
      },
      function (err, manager) {
        if (err) return res.sendResult(500, null, err);
        res.sendResult(200, manager, "更新成功");
      }
    );
  }
);

//删除
router.delete(
  "/:id",
  (req, res, next) => {
    //   /1?roleId=1 req.params req.query  { id: '1' } { roleId: '1' }
    if (!req.params.id) {
      return res.sendResult(400, null, "用户ID不能为空");
    }
    if (isNaN(parseInt(req.params.id)))
      return res.sendResult(400, null, "用户ID必须是数字");
    if (req.params.id == 500)
      return res.sendResult(400, null, "不允许删除admin账户");
    next();
  },
  (req, res, next) => {
    ManagerService.deleteManager(req.params.id, function (err, manager) {
      if (err) return res.sendResult(500, null, err);
      res.sendResult(200, manager, "删除成功");
    });
  }
);

module.exports = router;
